package com.handpay.zztong.hp.ui;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.Button;

import com.handpay.zztong.hp.R;

/****
 * 自定获得验证码延时按钮
 * 
 * @author 李国红
 * 
 */
public class VerificationCodeButton extends Button
{
	
	public Handler		mHandler	= null;
	public Runnable		mCounter	= null;
	final static int	MAX			= 60;
	int					mLockTime	= MAX;
	int					mLockCount	= 0;
	String				btnName		= "";
	
	public VerificationCodeButton(Context context)
	{
		super(context);
	}
	
	public VerificationCodeButton(Context context, AttributeSet attrs,
			int defStyle)
	{
		super(context, attrs, defStyle);
	}
	
	public VerificationCodeButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		btnName = this.getText().toString();
		mHandler = new Handler();
        this.setTextColor(getResources().getColor(R.color.verify_btn));
	}
	
	/****
	 * 开始计算时间;
	 * 
	 * @param time
	 *            设置时间 以秒计算单位
	 */
	public void startLocker(int time)
	{
		if (mHandler == null)
			return;
		if (time > 0)
			mLockTime = time;
		mLockCount = 0;
		Enabled(false);
		if (mCounter != null)
		{
			mHandler.removeCallbacks(mCounter);
		}
		if (mCounter == null)
		{
			mCounter = new Runnable()
			{
				@Override
				public void run()
				{
					mHandler.postDelayed(mCounter, 1000);
					mLockCount++;
					if (btnName != null && btnName.trim().length() > 0)
						VerificationCodeButton.this.setText(btnName + "("
								+ (MAX - mLockCount) + ")");
					else
						cancelLocker();
					if (mLockCount >= mLockTime)
						cancelLocker();
					
				}
			};
		}
		mHandler.post(mCounter);
	}
	
	/***
	 * 解除时间
	 */
	public void cancelLocker()
	{
		if (btnName != null && btnName.trim().length() > 0)
			VerificationCodeButton.this.setText(btnName.replace("("
					+ (MAX - mLockCount) + ")", ""));
		mLockCount = 0;
		if (mCounter != null)
		{
			mHandler.removeCallbacks(mCounter);
			Enabled(true);
		}
	}
	
	/***
	 * 是否禁用控件
	 * 
	 * @param enabled
	 */
	private void Enabled(boolean enabled)
	{
		VerificationCodeButton.this.setEnabled(enabled);
	}
}
